<template>
  <!-- 报价弹窗 -->
  <el-dialog :title="title" top="100px" :visible.sync="dialogVisible" :close-on-click-modal="false" width="1160px" @close="close">
    <div class="form-box">

      <div class=" flex fbt">
        <el-descriptions class="margin-top" title="游戏内容" :column="3" border>

          <el-descriptions-item :span="3" :labelStyle="{width:'120px'}" label="发布时间">
            {{form.createTime}}
          </el-descriptions-item>
          <el-descriptions-item :labelStyle="{width:'120px'}" label="游戏名称">
            {{form.gameName}}
          </el-descriptions-item>
          <el-descriptions-item label="区服" :labelStyle="{width:'120px'}">
            {{form.region}}
          </el-descriptions-item>
          <el-descriptions-item label="实名" :labelStyle="{width:'120px'}">
            {{form.relname}}
          </el-descriptions-item>
          <el-descriptions-item label="简介" :span="3" :labelStyle="{width:'120px'}">
            <div style="max-height: 300px;overflow-y: auto;white-space: pre-wrap">
              {{form.des}}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="图片" :span="3" :labelStyle="{width:'120px'}">
            <div class="flex img-box">
              <el-image :src="item" @click="imgView(list,ind)" v-for="(item, ind) in list" :key="item" class="lin-item"></el-image>
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <div class="inputBox">

          <el-descriptions class="margin-top" title="报价信息" :column="1" border>
            <template slot="extra">
              <el-button style="margin-right:10px" type="primary" size="small" @click="AIgujia">AI估价</el-button>
            </template>
            <el-descriptions-item label="" :span="3" :labelStyle="{width:'0',padding:0}">
              <el-form :model="form" ref="form" :rules="rules" class="demo-ruleForm">
                <div v-if="isEdit" style="margin-bottom: 10px;border-radius: 2px; background-color: #6c5dd3fa;">
                  <el-statistic v-if="baojiaEndTime" format="HH小时mm分钟ss秒" @finish="hilarity" :value="baojiaEndTime" time-indices title="">
                    <template slot="prefix">
                      <span style="font-size: 13px;color: #fff;line-height: 30px;">该商品距离出价结束还有</span>
                    </template>
                  </el-statistic>
                </div>
                <el-form-item label="报价" prop="price">
                  <el-input-number  :disabled="!isEdit || form.myMaxCount >= 5" :precision="2" :controls="false" v-model="form.price" placeholder="请输入您的报价" />
                </el-form-item>
                <div class="tip">提示：每个商品只能报5次，请填写你的最高回收价，以免与宝贝擦肩而过哦！</div>
                <div style="text-align: center;" v-if="isEdit && form.myMaxCount <5 ">
                  <!-- <el-button type="danger" v-if="from!='myedit'" @click="refuseLianmeng('form')" v-loading="loading">取消</el-button> -->
                  <el-button type="primary" @click="submitForm('form')" v-loading="loading">报价</el-button>
                </div>
              </el-form>
            </el-descriptions-item>
          </el-descriptions>
          <div style="height:30px"></div>
          <el-descriptions class="margin-top" title="当前进度" :column="1" border>
             <el-descriptions-item label="我的上一次报价">
                {{myPrice||0}}元
              </el-descriptions-item>
          
            <el-descriptions-item label="当前最高报价">
                {{form.maxPrice||0}}元
              </el-descriptions-item>
            <el-descriptions-item label="总报价次数" labelStyle="width:130px">
              {{form.maxCount||0}}
            </el-descriptions-item>
            <el-descriptions-item label="报价详情" v-if="backClueQuotations&&backClueQuotations.length">
              <div>
                <div class="flex fbt price_row" v-for="item in backClueQuotations" :key="item.id">
                  <div>{{ item.createTenantName }}</div>
                  <div style="color: red;">¥<b>{{ item.price }}</b></div>
                  <div class="zbsign " v-if="item.status==1">

                  </div>
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div class="gujiadialog">
        <el-dialog title="选择估价公式" :visible.sync="gujiaDialogShow" append-to-body width="500px" top="300px">
          <label>
            <b>估价公式：</b>
            <el-select v-model="selectGongshiId" placeholder="请选择估价公式">
              <el-option v-for="(item,i) in gujiaGongshiList" :key="i" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </label>
          <div class="center" style="margin-top: 10px;">
            <el-button @click="gujiaDialogShow = false;selectGongshiId = ''">取 消</el-button>
            <el-button type="primary" @click="AIgujiaDone">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import jingpaiApi from "@/api/jingpaishichang/index.js";
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import { tenantFormulaSettingsList } from "@/api/equation/equation";
export default {
  name: "",
  data() {
    return {
      dialogVisible: false,
      loading: false,
      isEdit: true,
      title: "报价",
      list: [], //图片list
      // 表单参数
      form: {
        price: "",
      },
      rules: {
        price: [{ required: true, message: "请输入报价", trigger: "blur" },
          // {
          // validator: (rule, value, callback) => {
          //   const maxPrice = this.form.maxPrice; 
          //   const priceNum = Number(this.form.price);
          //   const maxPriceNum = Number(maxPrice);
          //   if (!isNaN(maxPriceNum) && !isNaN(priceNum)) {
              
          //     if (priceNum < maxPriceNum) {
          //       return callback(new Error(`报价不能小于${maxPriceNum}（最高限价）`));
          //     }
          //   }
          //   callback();
          // },
          //    trigger: ["blur", "change"] // 报价或最高限价变化时都触发校验
          // }
        ],
      },
      backClueQuotations: [],
      from: "",
      type: "view",
      id: "",
      gujiaGongshiList: [],
      selectGongshiId: "",
      gujiaDialogShow: false,
      baojiaEndTime: "", //报价结束时间
      timer: null, //计时器
      jjscguize: {},
      outHours: "",
      outTimeDate: "",

      myPrice:0
    };
  },
  created() {
    this.getJJSCguize();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },

  methods: {
    // 打开弹窗
    open(id, flag) {
      console.log("id", flag);
      this.dialogVisible = true;
      this.type = flag;
      this.id = id;
      this.form = {
        price: "",
      };

      if (flag == "edit") {
        this.isEdit = true;
      } else {
        this.isEdit = false;
      }
      this.getDetail();
    },
    //获取竞价回收规则字典
    async getJJSCguize() {
      const res = await this.getDicts("biddingRule");
      if (res.data && res.data.length) {
        this.jjscguize = this.arrayToObject(res.data, "dictLabel");
        if (this.jjscguize.bidTimeOut) {
          const hours = this.jjscguize.bidTimeOut.dictValue;
          if (hours > 0) {
            this.outHours = hours;
          }
        }
      }
    },
    // 计算倒计时的计时器
    // intervalFn() {
    //   this.timer = setInterval(() => {
    //     this.getEndTime();
    //   }, 1000);
    // },
    // 计算报价结束倒计时
    getEndTime() {
      const now = new Date();
      const end = new Date(this.outTimeDate);
      if (now >= end) {
        // 报价已结束
        this.isEdit = false;
      } else {
        // const shengyu = new Date(end.getTime() - now.getTime());
        this.baojiaEndTime = end;
        console.log("%c Line:130 🍷 this.baojiaEndTime", "color:#e41a6a", this.baojiaEndTime);
      }
    },
    hilarity() {
      // 报价已结束
      this.isEdit = false;
    },
    // 获取估价公式
    getGongshiList(gameId) {
      tenantFormulaSettingsList({
        gameId: gameId,
      }).then((res) => {
        this.gujiaGongshiList = res.rows;
      });
    },
    // AI估价 打开公式列表选择
    AIgujia(row) {
      this.selectGongshiId = "";
      this.getGongshiList(this.form.gameId);
      this.gujiaDialogShow = true;
    },
    // 估价
    AIgujiaDone() {
      if (!this.selectGongshiId) {
        return this.$alert("请选择估价公式！");
      }
      onSelfApi
        .backCluebiddinggujia({
          id: this.form.id,
          tenantFormulaSettingsId: this.selectGongshiId,
        })
        .then((res) => {
          this.gujiaDialogShow = false;
          this.$alert(`${"估价成功！AI价格：¥" + res.data}`);
        })
        .catch((err) => {
          this.gujiaDialogShow = false;
          this.$alert(`估价失败！请检查估价公式是否正确！`);
        });
    },
    // 查询详情
    getDetail() {
      jingpaiApi.getbackClueInfo(this.id).then((res) => {
        console.log("%c Line:139 🥐 res", "color:#ea7e5c", res);
        this.form = { ...res.data };
        this.list = [];
    
          if (this.form.myPrice) {
           this.form.price = this.form.myPrice;
          }
        
        
        if(this.form.myPrice) {
           this.myPrice = res.data.myPrice
        }else {
           this.myPrice = res.data.price
        }
       
        if (
          this.form.backClueQuotations &&
          this.form.backClueQuotations.length &&
          (this.form.isExpired == 2 || this.form.acceptTenantId)
        ) {
          this.backClueQuotations = this.form.backClueQuotations;
        } else {
          this.backClueQuotations = [];
        }
        if (this.form.img) {
          let arr = [];
          let list = JSON.parse(this.form.img);
          if (list.length) {
            list.forEach((element) => {
              arr.push(element.url);
            });
            this.list = arr;
          }
        } else {
          this.list = [];
        }
        if (this.isEdit) {
          if (this.outHours) {
            const timearea = this.outHours * 60 * 60 * 1000;
            const orderTime = new Date(this.form.createTime).getTime();
            this.outTimeDate = new Date(orderTime + timearea);
          }
          this.getEndTime();
          // this.intervalFn();
        }
      });
    },
    // 报价
    submitForm(formName) {
      if (Number(this.form.price) <= 0) {
        return this.$alert("报价必须大于0");
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("%c Line:176 🎂 valid", "color:#ed9ec7", valid);
          this.$confirm("多报价5次,是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then((r) => {
            let obj = {
              price: this.form.price,
              backId: this.form.id,
            };
            jingpaiApi
              .backClueQuotation(obj)
              .then((res) => {
                if (res.code == 200) {
                  this.$alert("报价成功！");
                  this.$parent.getList();
                } else {
                  this.$alert(res.msg);
                }
              })
              .catch((err) => {
                this.$parent.getList();
              });

            this.dialogVisible = false;
          });
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },

    // 图片数组预览
    imgView(list, and) {
      this.$viewerApi({
        images: list,
        options: {
          initialViewIndex: and,
        },
      });
    },
    close() {
      this.baojiaEndTime = "";
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.$emit('close')
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.tip {
  color: red;
  margin-bottom: 10px;
}
.form-box {
  height: calc(100vh - 300px);
  overflow: auto;
}
.center {
  text-align: center;
}
.img-box {
  width: 500px;
}
.img-box {
  flex-wrap: wrap;
}
.lin-item {
  width: 100px;
  height: 100px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
}

.inputBox {
  width: 350px;
  margin-left: 20px;
  flex-shrink: 0;
  // border: 1px solid #ccc;
  // border-radius: 5px;
  // padding: 15px;
}
.price_row {
  font-size: 15px;
  padding: 5px 15px;
  border-bottom: 1px solid #f3f3f3;
  position: relative;
  padding-left: 35px;
  &:last-child {
    border-bottom: none;
  }
  .zbsign {
    position: absolute;
    color: #fff;
    top: 5px;
    left: 0;
    font-size: 11px;
    width: 25px;
    height: 25px;
    border-radius: 50%;
    // border: 1px solid #6c5dd3;
    background: #6d5dd3b7;
    text-align: center;
    background-image: url("../../../assets//images/chengjiao.png");
    background-size: 15px 15px;
    background-position: center;
    background-repeat: no-repeat;
  }
}
::v-deep .gujiadialog .el-dialog {
  margin-top: 300px !important;
}


// ::v-deep .el-statistic .number {
//   color: #6c5dd3;
//   font-size: 32px;
//   font-weight: bold;
//   margin-top: 5px;
// }
::v-deep .el-statistic .number {
  font-size: 16px !important;
  color: #f4f81e !important;
  margin-top: 0 !important;
}
</style>
